package com.jiadakeji.ppm.modules.invoice.service;


import com.jiadakeji.ppm.common.utils.DateUtils;
import com.jiadakeji.ppm.common.utils.InvoiceUtils;
import com.jiadakeji.ppm.common.utils.UrlUtils;
import com.jiadakeji.ppm.common.utils.XmlUtils;
import com.jiadakeji.ppm.modules.business.dao.TaxRateDao;
import com.jiadakeji.ppm.modules.business.entity.FeeCharge;
import com.jiadakeji.ppm.modules.business.entity.FeeReceive;
import com.jiadakeji.ppm.modules.business.entity.TaxRate;
import com.jiadakeji.ppm.modules.invoice.entity.*;
import com.jiadakeji.ppm.modules.sys.utils.UserUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class FillingInvoiceService {

    @Autowired
    private CounterService counterService;



    private Logger logger = LoggerFactory.getLogger(FillingInvoiceService.class);
    private String invioceAddr = "http://124.225.17.145:8082/SKServer/SKDo";


    @Autowired
    private TaxRateDao taxRateDao;




    public Content setFeeContent(FeeReceive feeReceive, FeeCharge feeCharge, List<Goods> list) {
        Content content = new Content();
        double jehj = 0.00, sehj = 0.00, jshj = 0.00;       //金额合计、税额合计、价税合计
        for(Goods goods : list){
            jehj += goods.getJe();
            sehj += goods.getSe();
        }
        jshj = jehj + sehj;
        BigDecimal jehjTemp = new BigDecimal(jehj);
        BigDecimal sehjTemp = new BigDecimal(sehj);
        BigDecimal jshjTemp = new BigDecimal(jshj);
        double jehjReal = jehjTemp.setScale(2, RoundingMode.HALF_UP).doubleValue();
        double jshjReal = jshjTemp.setScale(2,RoundingMode.HALF_UP).doubleValue();
        double sehjReal = sehjTemp.setScale(2,RoundingMode.HALF_UP).doubleValue();
        content.setHjje(jehjReal);
        content.setHjse(sehjReal);
        content.setJshj(jshjReal);

        content.setKpr(UserUtils.getUser().getName());
        content.setSkr("林丹丹");
        content.setFhr("卢芳友");
        content.setFplxdm("007");
        content.setTspz("00");

        String bz =  feeCharge.getCommunityName()+feeCharge.getBuildingName()+"-"+feeCharge.getRoom().getCode()+"  "+DateUtils.formatDate(feeCharge.getFeeMonth().getCurrentMonth(),"yyyy-MM")+"物业费\n";
        content.setBz(bz);

        return content;
    }

    public List<Goods> setGoods(FeeCharge feeCharge, FeeReceive feeReceive, SalesGoods salesGoods) {
        double fellbackMoney = 0.0;


        if(feeCharge.getFeebackMoney() != null) {
            fellbackMoney = feeCharge.getFeebackMoney();
        }
        List<Goods> list = new ArrayList<>();
        addGoodsToList(list,feeCharge);
        if(fellbackMoney != 0.0){
            Goods goods1 = new Goods();
            // todo 没有违约金编码，暂用电费编码
           List<TaxRate> taxRates =  taxRateDao.findByType(InvoiceUtils.TAX_TYPE_FEEBACK);
           TaxRate t = taxRates.get(0);
           Double sf = t.getBeforeRate();
           if(t.getChangeDate().getTime()<System.currentTimeMillis()){
               sf = t.getAfterRate();
           }
            setGoods(goods1,fellbackMoney,sf,t.getSpbm());
            goods1.setSpmc(t.getSpName());
            goods1.setXh(String.valueOf(list.size()+1));
            list.add(goods1);
        }

        return list;
    }

    /**
     * 根据台账进行相关费用项目填充
     * @param list
     * @param feeCharge
     */
    private void addGoodsToList(List<Goods> list, FeeCharge feeCharge) {
        Double avgElecFee = feeCharge.getAvgElecFee();
        List<TaxRate> taxRates = null;
        if(null !=avgElecFee && !avgElecFee.equals(0.0)){
           taxRates = taxRateDao.findByType(InvoiceUtils.TAX_TYPE_AVG_ELEC);
            addGoods0(list,avgElecFee,taxRates.get(0));
        }

        Double avgWaterFee = feeCharge.getAvgWaterFee();
        if(null != avgWaterFee && !avgWaterFee.equals(0.0)){
            taxRates = taxRateDao.findByType(InvoiceUtils.TAX_TYPE_AVG_WATER);
            addGoods0(list,avgWaterFee,taxRates.get(0));
        }

        Double manageFee = feeCharge.getManageFee();
        if(null != manageFee && !manageFee.equals(0.0)){
            taxRates = taxRateDao.findByType(InvoiceUtils.TAX_TYPE_MANAGE_FEE);
            addGoods0(list,manageFee,taxRates.get(0));
        }

        Double carMonthFee = feeCharge.getCarMonthFee();
        if(null != carMonthFee && !carMonthFee.equals(0.0)){
            taxRates = taxRateDao.findByType(InvoiceUtils.TAX_TYPE_CAR_PART_FEE);
            addGoods0(list,carMonthFee,taxRates.get(0));
        }

        Double elevatorFee = feeCharge.getElevatorFee();
        if(null != elevatorFee && !elevatorFee.equals(0.0)){
            taxRates = taxRateDao.findByType(InvoiceUtils.TAX_TYPE_ELEVATOR_FEE);
            addGoods0(list,elevatorFee,taxRates.get(0));
        }

        Double secondPushElecFee =feeCharge.getSecondPushElecFee();
        if(null != secondPushElecFee && !secondPushElecFee.equals(0.0)){
            taxRates = taxRateDao.findByType(InvoiceUtils.TAX_TYPE_SECOND_PUSH_FEE);
            addGoods0(list,secondPushElecFee,taxRates.get(0));
        }


    }

    private void addGoods0(List<Goods> list,Double price,TaxRate t){
        Goods goods = new Goods();
        goods.setSpsl("1");
        goods.setDw("月");
        Double sf = t.getBeforeRate();
        if(t.getChangeDate().getTime()<System.currentTimeMillis()){
            sf = t.getAfterRate();
        }
        setGoods(goods,price,sf,t.getSpbm());
        goods.setDj(String.valueOf(goods.getJe()));
        goods.setSpmc(t.getSpName());
        goods.setXh(String.valueOf(list.size()+1));
        list.add(goods);
    }

    /**
     * 填入每一条商品相关信息
     * @param goods
     * @param fee
     * @param rate
     * @param spbm
     */
    private void setGoods(Goods goods, double fee, double rate, String spbm) {
        BigDecimal jeTemp = new   BigDecimal(fee/(1+rate));
        double je = jeTemp.setScale(2,RoundingMode.HALF_UP).doubleValue();
        BigDecimal temp = new   BigDecimal(fee - je);
        double se = temp.setScale(2,   RoundingMode.HALF_UP).doubleValue();

        goods.setFphxz("0");
        goods.setSl(rate);
        goods.setJe(je);
        goods.setSe(se);
        goods.setHsbz("1");
        goods.setSpbm(spbm);
        goods.setYhzcbs("0");

    }






    public List<Goods> setBlankGoods() {
        List<Goods> list = new ArrayList<>();
        for(int i = 0; i < 6; i++){
            Goods goods = new Goods();
            goods.setXh(String.valueOf(i+1));
            goods.setYhzcbs("0");
            list.add(goods);
        }
        return list;
    }



    /**
     *对于空白开具进行税率填充
     * @param group
     */
    public void updateGoodsRate(List<Goods> group) {
        TaxRate taxRate = new TaxRate();
        for(Goods goods : group){
            if(null != goods.getSpbm()){
                taxRate.setSpbm(goods.getSpbm());
                List<TaxRate> taxRateList =  taxRateDao.findList(taxRate);
                if(null != taxRateList && !taxRateList.isEmpty()){
                    goods.setSl(taxRateList.get(0).getAfterRate());
                }
            }

        }
    }

    public List<SearchInvioceInfo> staticInvioce(FindInvioceCondition findInvioceCondition) {
        List<SearchInvioceInfo> searchInvioceInfoList = new ArrayList<>();          //统计使用的大list
        Date startDate = new Date();
        if(findInvioceCondition != null && findInvioceCondition.getStartDate() != null){
            startDate = findInvioceCondition.getStartDate();
        }
        String fplxdm = "007",searchType = "1";        //从左往右 发票类型代码 查询方式
        String cxtjDate = DateUtils.formatDateTimeYYYYMMDD(startDate);
        String cxtj = cxtjDate + cxtjDate;              //查询条件
        if(findInvioceCondition != null && findInvioceCondition.getSearchType() != null){
            fplxdm = findInvioceCondition.getFplxdm();
            searchType = findInvioceCondition.getSearchType();
        }
        findInvioceCondition.setStartDate(DateUtils.parseDate(cxtjDate));

        List<String> counterList = new ArrayList<>();               //统计使用的柜台号
        if(UserUtils.getUser().isAdmin()
                || UserUtils.getUser().getRoleNames().contains("桂林洋管理员")
                || UserUtils.getUser().getRoleNames().contains("出纳员")){         //管理员遍历全部柜台进行查找
            List<Counter> counters = counterService.findList(new Counter());
            for(Counter counter : counters){
                counterList.add(counter.getAccount());
            }
        }else {
            String loginCounter = (String) SecurityUtils.getSubject().getSession().getAttribute("counter");
            counterList.add(loginCounter);
        }

        for(String counter : counterList) {
            String requestXml = "<?xml version=\"1.0\" encoding=\"gbk\"?>\n" +
                    "<business id=\"10010\" comment=\"发票查询\">\n" +
                    "<body yylxdm=\"1\">\n" +
                    "<kpzdbs>" + counter + "</kpzdbs>\n" +
                    "<fplxdm>" + fplxdm + "</fplxdm>\n" +
                    "<cxfs>" + searchType + "</cxfs>\n" +
                    "<cxtj>" + cxtj + "</cxtj>\n" +
                    "</body>\n" +
                    "</business>";

            logger.info("发票查询xml" + requestXml);
            String url = invioceAddr;
            String responseXml = UrlUtils.sendPost(url, requestXml, "GBK");
//            responseXml = responseXml.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", "");
//            responseXml = responseXml.replace("<?xml version=\"1.0\" encoding=\"gbk\"?>","<?xml version=\"1.1\" encoding=\"gbk\"?>");

            SearchReturnData searchReturnData = (SearchReturnData) XmlUtils.xmlToObject(SearchReturnData.class, responseXml);
            List<SearchInvioceInfo> list = new ArrayList<>();           //每个帐号下的小list
            if (searchReturnData != null && searchReturnData.getSearchInvioceDetail() != null && searchReturnData.getSearchInvioceDetail().getSearchInvioceReturnData() != null) {
                list = searchReturnData.getSearchInvioceDetail().getSearchInvioceReturnData().getSearchInvioceContent().getSearchInvioceInfoList();
            }
            searchInvioceInfoList.addAll(list);
        }

        return searchInvioceInfoList;
    }

}
